<template>
  <div class="login-page">
    <div v-if="licenseShow" class="license-form-wrapper">
      <el-form ref="licenseFormRef" :model="licenseData" :rules="licenseRules" action="javascript:void(0)"
               class="login-form" label-position="top">
        <div class="login-welcome">{{ $t('home.registration') }}</div>
        <el-form-item :label="$t('home.name')" prop="companyName">
          <el-input v-model="licenseData.companyName" :placeholder="$t('home.company')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('home.network')" prop="macNum">
          <el-select v-model="licenseData.macNum" :placeholder="$t('home.physical')" clearable style="width: 100%">
            <el-option v-for="item in macNumList" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('home.Key')" prop="secretKey">
          <el-input v-model="licenseData.secretKey" :placeholder="$t('home.enterKey')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('home.License')" prop="license">
          <el-input v-model="licenseData.license" :placeholder="$t('home.product')"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button :loading="loading" auto-insert-space class="full-width" size="default" type="primary"
                     @click="handleLicense">{{ $t('home.Register') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-else class="form-wrapper">
      <el-form action="javascript:void(0)" :model="user" class="login-form" ref="loginFormRef" :rules="loginRules">
        <div class="login-welcome">{{ title }}</div>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" v-model="username" size="default" placeholder="请输入您的用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input :prefix-icon="Lock" v-model="password" type="password" size="default" placeholder="请输入您的密码"
                    @keyup.enter="handleLogin">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button :loading="loading" size="default" type="primary" class="full-width" auto-insert-space
                     @click="handleLogin">登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>

  </div>
</template>

<script setup lang="ts">
import * as LoginService from '@/services/login-service';
import * as license from '@/services/system/license';
import {reactive, ref, toRefs, onMounted, nextTick, computed} from 'vue';
import {useRouter} from 'vue-router';
import {PAGE_HOME} from '@/constants/page-url-constants';
import {UserActionTypes} from '@/store/modules/user/action-types'
import {useStore} from '@/store'
import {Lock, User} from '@element-plus/icons-vue'
import {ElMessage} from "element-plus/es";
import {configData, getStatic} from "@/utils/common";
import {Base64} from 'js-base64';
import {cloneDeep} from "lodash";

const router = useRouter();
const store = useStore()
const loginFormRef = ref(null)
const licenseFormRef = ref(null)

const user = reactive({
  grant_type: 'password',
  username: '',
  password: '',
} as LoginService.LoginParam);
const state = reactive({
  loginRules: {
    username: [{required: true, message: '本项必填', trigger: 'blur'}],
    password: [{required: true, message: '本项必填', trigger: 'blur'},]
  },
  passwordType: 'password',
  loading: false,
  showDialog: false,
  capsTooltip: false,
  redirect: '',
  otherQuery: {},
  //许可证
  licenseShow: false,
  licenseData: {
    companyName: '',
    license: '',
    secretKey: '',
    macNum: ''
  } as license.LicenseData,
  licenseRules: {
    companyName: [{required: true, message: '本项必填', trigger: 'blur'}],
    license: [{required: true, message: '本项必填', trigger: 'blur'}],
    secretKey: [{required: true, message: '本项必填', trigger: 'blur'}],
    macNum: [{required: true, message: '本项必填', trigger: 'blur'}],
  },
  macNumList: [] as Array<string>,
  title: computed(() => {
    return window.apiObj.loginTitle
  })
})
const {loginRules, loading, licenseData, licenseShow, licenseRules, macNumList, title} = toRefs(state)
const {username, password} = toRefs(user)

onMounted(async () => {
  let test = await window.apiObj
  console.log(test)
  // setTimeout(()=>{
  //判断许可证
  // license.check().then(({data}) => {
  //   state.licenseShow = data;
  //   if (data) {
  //     加载机器信息
      // license.getComputerInfo().then(({data}) => {
      //   state.macNumList = data;
      // })
    // }
  // });
  // },5000)


})
function login(){
  router.push('/setlayout/index')
}
const handleLogin = () => {
  (loginFormRef.value as any).validate(async (valid: boolean) => {
    if (valid) {
      state.loading = true

      let params = cloneDeep(user)
      // params.password = Base64.encode(params.password)
      store.dispatch(UserActionTypes.ACTION_LOGIN, params).then((res) => {
        store.dispatch(UserActionTypes.ACTION_GET_USER_INFO, undefined).then(()=>{
        // setTimeout(()=>{
          router.push({
          path: '/home',
        })
        // },1000)



        })

        state.loading = false
      }).catch(response => {
        state.loading = false
        // ElMessage.error(response||'登录失败');
      })
      // await store.dispatch(UserActionTypes.ACTION_GET_USER_INFO, undefined)

      // // Just to simulate the time of the request
      // setTimeout(() => {
      //   state.loading = false
      // }, 0.5 * 1000)
    } else {
      return false
    }
  })
}

const handleLicense = () => {
  (licenseFormRef.value as any).validate(async (valid: boolean) => {
    if (valid) {
      state.loading = true;
      license.add(state.licenseData).then(() => {
        location.reload();
      });
    } else {
      return false
    }
  })
}


</script>

<style lang="scss" scoped>
.login-page {
  background: url('@/assets/images/login.jpg') center no-repeat;
  background-size: cover;
  height: 100%;
  overflow: auto;
}

.form-wrapper {
  width: 380px;
  background-color: #ffffffa1;
  border-radius: 10px;
  margin: 200px auto;
  padding: 40px;
  box-shadow: 0 0 20px #959595;
}

.license-form-wrapper {
  width: 580px;
  background-color: #ffffffa1;
  border-radius: 10px;
  margin: 200px auto;
  padding: 40px;
  box-shadow: 0 0 20px #959595;
}

.login-welcome {
  margin-bottom: 15px;
  font-size: 18px;
  font-weight: 600;
}
</style>
